@file:Suppress("PLUGIN_WARNING")

package com.shiwaixiangcun.customer.module.heath

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.google.gson.reflect.TypeToken
import com.jaeger.recyclerviewdivider.RecyclerViewDivider
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.adapter.AdapterHealthReport
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.module.houserenting.CommonDataEntity
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.ui.fragment.LazyFragment
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import com.shiwaixiangcun.customer.utils.RefreshTokenUtil
import com.shiwaixiangcun.customer.widget.CustomLoadMoreView
import kotlinx.android.synthetic.main.layout_fragment_report.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Author   Administrator
 * Date     2018/1/22
 * Desc     健康体检报告
 *
 * @author Administrator
 */

class FragmentReport : LazyFragment() {

    companion object {
        val BUG_TAG = "fragmentReport"
        val CHANGE_TAB = 0x1010
        fun newInstance(userID: Long?): FragmentReport {
            val f = FragmentReport()
            val args = Bundle()
            args.putLong("userID", userID!!)
            f.arguments = args
            return f

        }
    }

    private var strToken: String? = null
    private var refreshToken: String? = null
    private var userID: Long? = null
    private var mCurrentPage = 1
    private var mPageSize = 20
    private var mAdapter: AdapterHealthReport? = null
    private var mDataList: MutableList<HealthReportData>? = null
    private var emptyView: View? = null
    private var tvEmpty: TextView? = null
    private var ivEmpty: ImageView? = null
    override fun getContentViewLayoutID(): Int {
        return R.layout.layout_fragment_report
    }

    override fun initViewsAndEvents(view: View) {

        strToken = AppSharePreferenceMgr.get(activity?.applicationContext, ConfigSps.CURRENT_TOKEN, "") as String
        refreshToken = AppSharePreferenceMgr.get(activity, ConfigSps.CURRENT_REFRESH_TOKEN, "") as String
        mCurrentPage = GlobalConfig.first_page
        mPageSize = GlobalConfig.page_size

        emptyView = LayoutInflater.from(activity).inflate(R.layout.layout_common_empty, null, false)

        tvEmpty = emptyView?.findViewById(R.id.tv_empty)
        ivEmpty = emptyView?.findViewById(R.id.iv_empty)
        ivEmpty?.setImageResource(R.drawable.empty_health_report)
        tvEmpty?.text = "您还没有体检报告~"
        mDataList = ArrayList()
        mAdapter = AdapterHealthReport(mDataList)
        rv_health_report.layoutManager = LinearLayoutManager(mContext)
        rv_health_report.adapter = mAdapter
        val divider = RecyclerViewDivider.Builder(context)
                .setColorRes(R.color.color_divider_0_1)
                .setMarginLeft(16f)
                .setMarginRight(16f)
                .setStyle(RecyclerViewDivider.Style.BETWEEN)
                .setSize(0.5f)
                .build()
        rv_health_report.addItemDecoration(divider)
        mAdapter?.setLoadMoreView(CustomLoadMoreView())
        mAdapter?.setOnLoadMoreListener({
            mCurrentPage += 1
            userID?.let { initData(it, true) }
        }, rv_health_report)

        mAdapter?.setOnItemClickListener { adapter, view, position ->
            val healthReportData = adapter.data[position] as HealthReportData
            val bundle = Bundle()
            bundle.putLong("reportId", healthReportData.id)
            readyGo(ReportDetailActivity::class.java, bundle)
        }

    }

    override fun onFirstUserVisible() {
        if (userID == 0L) {
            return
        }
        mCurrentPage = 1
        mAdapter?.setEnableLoadMore(false)
        userID?.let { initData(it, false) }

    }

    override fun onUserVisible() {
        mCurrentPage = 1
        mAdapter?.setEnableLoadMore(false)
        userID?.let { initData(it, false) }
    }

    override fun onUserInvisible() {

    }

    override fun destroyViewAndThing() {
        EventUtil.getInstance().unregister(this)

    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val bundle = arguments
        if (bundle != null) {
            userID = bundle.getLong("userID")
        }
        EventUtil.getInstance().register(this)
    }

    /**
     * EventBus
     *
     * 数据更新
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {
        when (simpleEvent.mEventType) {

        //当切换家人的时候执行
            SimpleEvent.HEALTH_CHANGE_FAMILY -> {
                when (simpleEvent.mEventValue) {
                    CHANGE_TAB -> {
                        val id = simpleEvent.data as Long
                        userID = id
                        if (this.isUserVisiable) {
                            Log.e(BUG_TAG, "change")
                            mAdapter?.setEnableLoadMore(false)
                            mCurrentPage = 1
                            initData(userID!!, false)
                        }

                    }
                }
            }

            else -> {
                return
            }
        }

    }


    fun initData(id: Long, isLoadMore: Boolean) {
        OkGo.get<String>(GlobalApi.HEALTH_REPORT)
                .params("page.pn", mCurrentPage)
                .params("page.size", mPageSize)
                .params("access_token", strToken)
                .params("customerId", id)
                .execute(object : StringCallback() {
                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        mAdapter?.setEnableLoadMore(true)
                        mAdapter?.loadMoreFail()
                    }

                    override fun onSuccess(response: Response<String>?) {

                        val type = object : TypeToken<CommonDataEntity<HealthReport>>() {}.type
                        val reportData = JsonUtil.fromJson<CommonDataEntity<HealthReport>>(response?.body(), type)
                        when (reportData.responseCode) {
                            ResponseConfig.SUCCESS -> {
                                val size = reportData.data.elements.size
                                if (isLoadMore) {
                                    if (size > 0) {
                                        mDataList?.addAll(reportData.data.elements)
                                        mAdapter?.notifyDataSetChanged()
                                    }
                                    if (size == 0 || size < mCurrentPage) {
                                        mAdapter?.loadMoreEnd(false)
                                    } else {
                                        mAdapter?.loadMoreComplete()
                                    }
                                } else {
                                    mAdapter?.setEnableLoadMore(true)
                                    if (size == 0) {
                                        mDataList?.clear()
                                        mAdapter?.emptyView = emptyView
                                        mAdapter?.notifyDataSetChanged()
                                    } else {
                                        layout_nodata.visibility = View.GONE
                                        mDataList?.clear()
                                        mDataList?.addAll(reportData.data.elements)
                                        mAdapter?.notifyDataSetChanged()
                                    }
                                }
                            }
                            ResponseConfig.TOKEN_INVALID -> {
                                RefreshTokenUtil.refreshToken(mContext, refreshToken)
                            }
                            else -> {
                                Log.e(BUG_TAG, "加载失败")

                            }
                        }

                    }

                })

    }


}
